package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * @Author xuejiao
 * Data 2025/5/2 22:19
 */
@Component
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localhost;
    @Override
    public String savePicture(MultipartFile multipartFile) {

        //1.创建目录
        File dir = new File(localhost);
        if(!dir.exists()) {
            dir.mkdirs();
        }

        //2.创建索引
        //yxj.jpg -->xxx.jpg
        //yxj.jpg .jpg  xxx xxx.jpg
        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(
                filename.lastIndexOf("."));
        filename = UUID.randomUUID()+suffix;

        //3.保存图片
        try {
            multipartFile.transferTo(new File(localhost+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return filename;
    }
}
